package com.hooper.solution.day8;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/02/04/23:54
 */
public class Solutions {
    /**
     * 剑指 Offer 53 - I. 在排序数组中查找数字 I
     * 统计一个数字在排序数组中出现的次数。
     * 示例 1:
     * <p>
     * 输入: nums = [5,7,7,8,8,10], target = 8
     * 输出: 2
     * 示例 2:
     * <p>
     * 输入: nums = [5,7,7,8,8,10], target = 6
     * 输出: 0
     */

    public int search(int[] nums, int target) {
//        return (int) Arrays.stream(nums).filter(i -> i == target).count();
        int startIdx = findFirst(nums, target);
        if (startIdx == -1) return 0;
        int lastIdx = findLast(nums, target);
        return lastIdx - startIdx + 1;
    }

    private int findLast(int[] nums, int target) {
        int len = nums.length;
        if (len == 0) return -1;
        int left = 0, right = len - 1;
        while (left < right) {
            int mid = left + (right - left + 1) / 2;
            if (nums[mid] <= target) {
                //若nums[mid] <= target
                //则大于target的元素的区间为[mid,right]
                left = mid;
            } else {
                //若大于target,则搜索区间为[left, mid -1]
                right = mid - 1;
            }
        }
        return left;
    }

    private int findFirst(int[] nums, int target) {

        int len = nums.length;
        if (len == 0) return -1;
        int left = 0, right = len - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                //若mid的下标对应的值等于target，则mid有可能是第一个，
                // 但mid+1一定不是第一个
                //因此搜索区间就变为：[left,mid]
                //若num[mid] > target 则搜索区间变为[left ,mid -1]
                //这里将等于和大于的情况合并了
                right = mid;
            }
        }
        //循环结束时left == right
        //数组中也可能没有target元素
        return nums[left] == target ? left : -1;
    }

}
